document.addEventListener('DOMContentLoaded', function () {
    // Function to fetch product data and update the modal
    async function loadProductData(productId) {
        try {
            const response = await fetch(`/product/${productId}`);
            if (!response.ok) throw new Error('Network response was not ok');
            const product = await response.json();

            const { name, picture, price, description, stock, categoryName } = product;

            document.getElementById('product-title').innerText = name;
            document.getElementById('price').innerText = `$${price.toFixed(2)}`;
            document.getElementById('description').innerText = description || 'No description available.';
            document.getElementById('sku').innerText = 'N/A';
            document.getElementById('availability').innerText = stock > 0 ? '还有库存' : '没库存了';
            document.getElementById('category').innerText = categoryName || 'No category';
            document.getElementById('image1').src = picture;
        } catch (error) {
            console.error('Error fetching product data:', error);
        }
    }

    // Event listener for modal show event
    $('#myModal').on('show.bs.modal', function (event) {
        const button = $(event.relatedTarget);
        const productId = button.data('product-id');
        loadProductData(productId);
    });
});
